package com.atldy.commerce.service;

import cn.hutool.core.collection.CollUtil;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

/**
 * @version 1.0
 * @Author: li-dong-yang
 * @CreateTime: 2021-09-12 17:52
 * @Description： 请求缓存 Hystrix
 */
@Slf4j
public class CacheHystrixServiceCommand extends HystrixCommand<List<ServiceInstance>> {

    private final NacosClientService nacosClientService;

    private final String serviceId;

    private final static HystrixCommandKey COMMAND_KEY = HystrixCommandKey.Factory.asKey("CacheHystrixServiceCommand");


    public CacheHystrixServiceCommand(NacosClientService nacosClientService, String serviceId) {
        super(
                HystrixCommand.Setter
                        .withGroupKey(HystrixCommandGroupKey.Factory.asKey("nacosClientService"))
                        .andCommandKey(COMMAND_KEY)
        );

        this.nacosClientService = nacosClientService;
        this.serviceId = serviceId;
    }

    @Override
    protected List<ServiceInstance> run() throws Exception {
        log.info("use hystrix command annotation to get nacos client info: [{}], [{}]",
                serviceId, Thread.currentThread().getName());
        return nacosClientService.getServiceInstance(serviceId);
    }

    /**
     * <h3>降级兜底方法</h3>
     */
    @Override
    protected List<ServiceInstance> getFallback() {
        log.error("服务名称是：{}", serviceId);
        return CollUtil.newArrayList();
    }

    /**
     * <h3>请求缓存</h3>
     */
    @Override
    protected String getCacheKey() {
        return serviceId;
    }

    /**
     * <h3>清除请求缓存</h3>
     */
    public static void clearRequestCache(String serviceId) {
        HystrixRequestCache.getInstance(COMMAND_KEY
                , HystrixConcurrencyStrategyDefault.getInstance())
                .clear(serviceId);
    }
}